<template>
  <div class="app-container">
    <el-card class="user-profile" shadow="hover">
      <div slot="header" class="clearfix">
        <span>个人中心</span>
      </div>
      <el-table :data="[form]" style="width: 100%" border>
        <el-table-column label="头像" width="130" align="center">
          <template #default="scope">
            <img :src="scope.row.userAvatar" alt="用户头像" class="user-avatar">
          </template>
        </el-table-column>
        <el-table-column  align="center" label="昵称" prop="userName"></el-table-column>
        <el-table-column  align="center" label="账号" prop="userAccount" width="150"></el-table-column>
        <el-table-column  align="center" label="省" prop="userProvince" :formatter="convertCode"></el-table-column>
        <el-table-column  align="center" label="市" prop="userCity" :formatter="convertCode"></el-table-column>
        <el-table-column  align="center" label="县" prop="userRegion" :formatter="convertCode"></el-table-column>
        <el-table-column  align="center" label="详细地址" prop="userAddress" width="200"></el-table-column>
        <el-table-column  align="center" label="手机号" prop="userPhone" width="150"></el-table-column>
        <el-table-column  align="center" label="性别" prop="userGender">
          <template #default="scope">
            {{ userGender[scope.row.userGender] || '未知' }}
          </template>
        </el-table-column>
        <el-table-column  align="center" label="年龄" prop="userBirthday">
          <template #default="scope">
            {{ calculateAge(scope.row.userBirthday) }}
          </template>
        </el-table-column>
        <el-table-column  align="center" label="备注" prop="userRemark"></el-table-column>
      </el-table>
      <div class="text-right">
        <el-button type="primary" @click="handleEdit">编辑</el-button>
        <el-button type="danger" @click="handleLogout">注销</el-button>
      </div>
    </el-card>

    <el-dialog :visible.sync="dialogVisible" title="编辑个人信息" custom-class="edit-dialog">
      <el-form :model="form" label-width="80px" ref="form">
        <el-row :gutter="20">
          <!--<el-form-item label="头像" prop="userAvatar">-->
          <!--  <image-upload v-model="form.userAvatar" placeholder="请上传图片"/>-->
          <!--</el-form-item>-->
          <el-col :span="12">
            <el-form-item label="昵称">
              <el-input v-model="form.userName"/>
            </el-form-item>
            <el-form-item label="账号">
              <el-input v-model="form.userAccount" disabled/>
            </el-form-item>
            <div style="display: flex">
              <el-form-item label="省" prop="userProvince">
                <el-select v-model="form.userProvince" placeholder="请选择省" @change="refreshCity" style="width: 89px">
                  <el-option
                      v-for="item in filteredProvinces"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="市" prop="userCity">
                <el-select v-model="form.userCity" placeholder="请选择市" @change="refreshArea" style="width: 89px">
                  <el-option
                      v-for="item in filteredCities"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="县" prop="userRegion">
                <el-select v-model="form.userRegion" placeholder="请选择区" style="width: 89px">
                  <el-option
                      v-for="item in filteredRegions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="详细地址">
              <el-input v-model="form.userAddress"/>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="form.userPhone"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="form.userGender">
                <el-option v-for="type in userGenderJson" :label="type.label" :value="type.value" :key="type.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="生日">
              <el-date-picker
                  v-model="form.userBirthday"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.userRemark" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addUser, updateUser} from "@/api/user/user";
import areas from "@/utils/areas";
import {getUserInfo} from "@/utils/auth";
import {convertCode} from "@/utils/areasUtil";

export default {
  name: "UserView",
  data() {
    return {
      areas: areas,
      cityList: [],
      districtList: [],
      userTypeJson: [
        {value: 1, label: '管理员'},
        {value: 2, label: '用户'},
      ],
      userTypes: {
        '1': '管理员',
        '2': '用户'
      },
      userGenderJson: [
        {value: 1, label: '男'},
        {value: 2, label: '女'},
      ],
      userGender: {
        '1': '男',
        '2': '女'
      },
      userStatus: {
        '1': '正在使用',
        '2': '已注销'
      },
      userStatusJson: [
        {value: 1, label: '正在使用'},
        {value: 2, label: '已注销'},
      ],
      loading: false,
      form: {},
      dialogVisible: false,
    };
  },
  computed: {
    filteredProvinces() {
      return this.areas.filter(item => item.type === 1);
    },
    filteredCities() {
      return this.areas.filter(item => item.parentId === this.form.userProvince);
    },
    filteredRegions() {
      return this.areas.filter(item => item.parentId === this.form.userCity);
    },
  },
  created() {
    this.form = getUserInfo();
    console.log(this.form);
  },
  methods: {
    refreshCity() {
      this.form.userCity = '';
      this.form.userRegion = '';
    },
    refreshArea() {
      this.form.userRegion = '';
    },
    convertCode,
    calculateAge(birthday) {
      const birthdayDate = new Date(birthday);
      if (isNaN(birthdayDate.getTime())) {
        console.error('Invalid date:', birthday);
        return '无效日期';
      }
      const today = new Date();
      let age = today.getFullYear() - birthdayDate.getFullYear();
      const m = today.getMonth() - birthdayDate.getMonth();
      if (m < 0 || (m === 0 && today.getDate() < birthdayDate.getDate())) {
        age--;
      }
      return age;
    },
    handleEdit() {
      this.dialogVisible = true;
    },
    handleLogout() {
      this.$confirm('确认注销账号吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 执行注销操作，比如清除token，跳转到登录页等
        this.$message.success('注销成功');
        // 清除用户信息和权限等
        // 跳转到登录页面或其他页面
      }).catch(() => {
        this.$message.info('已取消注销');
      });
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateUser(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.dialogVisible = false;
            });
          } else {
            addUser(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
            });
          }
        }
      });
    },
  }
};
</script>

<style> .app-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.user-profile {
  width: 90%;
  max-width: 1400px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.text-right {
  text-align: right;
  margin-top: 20px;
} </style>